﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PRO.Common;
using PRO.Entity;
using PRO.Config;
using Newtonsoft.Json;
using System.Data;
using PRO.DbProvider;

namespace PRO.Product
{
    public class ShopCart
    {
        /// <summary>
        /// 添加到购物车
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static bool AddToCart(ShopCartCookie info)
        {
            bool r = false;
            if (info.ID > 0)
            {
                List<ShopCartCookie> shoplist = new List<ShopCartCookie>();
                string json = Utils.GetCookie("ShopCart".DEC_Encode(BaseConfigs.DEC_KEY)).DEC_Decode(BaseConfigs.DEC_KEY);
                if (json.IsNullOrWhiteSpace())
                {
                    shoplist.Add(info);
                    r = true;
                }
                else
                {
                    try
                    {
                        shoplist = JsonConvert.DeserializeObject<List<ShopCartCookie>>(json);
                        ShopCartCookie shop = shoplist.Find(delegate(ShopCartCookie p) { return p.ID == info.ID; });
                        shoplist.Remove(shop);
                        if (shop != null)
                        {
                            shop.Count += info.Count;
                            shoplist.Add(shop);
                        }
                        else
                            shoplist.Add(info);
                        r = true;
                    }
                    catch
                    {
                        shoplist.Add(info);
                        r = true;
                    }
                }
                Utils.WriteCookie("ShopCart".DEC_Encode(BaseConfigs.DEC_KEY), JsonConvert.SerializeObject(shoplist).DEC_Encode(BaseConfigs.DEC_KEY), 60 * 24);
            }
            return r;
        }
        /// <summary>
        /// 从购物车中移除产品
        /// </summary>
        /// <param name="id">产品id</param>
        /// <returns></returns>
        public static bool DelItemToCart(int id)
        {
            bool r = false;
            List<ShopCartCookie> shoplist = new List<ShopCartCookie>();
            string json = Utils.GetCookie("ShopCart".DEC_Encode(BaseConfigs.DEC_KEY)).DEC_Decode(BaseConfigs.DEC_KEY);
            if (!json.IsNullOrWhiteSpace())
            {
                try
                {
                    shoplist = JsonConvert.DeserializeObject<List<ShopCartCookie>>(json);
                    ShopCartCookie shop = shoplist.Find(delegate(ShopCartCookie p) { return p.ID == id; });
                    shoplist.Remove(shop);
                }
                catch
                {
                }
            }
            Utils.WriteCookie("ShopCart".DEC_Encode(BaseConfigs.DEC_KEY), JsonConvert.SerializeObject(shoplist).DEC_Encode(BaseConfigs.DEC_KEY), 60 * 24);
            return r;
        }
        public static bool EditItemCounts(int id, int counts)
        {
            bool r = false;
            List<ShopCartCookie> shoplist = new List<ShopCartCookie>();
            string json = Utils.GetCookie("ShopCart".DEC_Encode(BaseConfigs.DEC_KEY)).DEC_Decode(BaseConfigs.DEC_KEY);
            if (!json.IsNullOrWhiteSpace())
            {
                try
                {
                    shoplist = JsonConvert.DeserializeObject<List<ShopCartCookie>>(json);
                    ShopCartCookie shop = shoplist.Find(delegate(ShopCartCookie p) { return p.ID == id; });
                    shoplist.Remove(shop);
                    shop.Count = counts;
                    shoplist.Add(shop);
                }
                catch
                {
                }
            }
            Utils.WriteCookie("ShopCart".DEC_Encode(BaseConfigs.DEC_KEY), JsonConvert.SerializeObject(shoplist).DEC_Encode(BaseConfigs.DEC_KEY), 60 * 24);
            return r;
        }
        /// <summary>
        /// 根据购物车cookie信息获取产品标题及价格
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public static DataTable GetCartItems(out decimal totalPrice)
        {
            DataTable dt = new DataTable();
            totalPrice = 0;
            List<ShopCartCookie> list = new List<ShopCartCookie>();
            string json = Utils.GetCookie("ShopCart".DEC_Encode(BaseConfigs.DEC_KEY)).DEC_Decode(BaseConfigs.DEC_KEY);
            if (!json.IsNullOrWhiteSpace())
            {
                try
                {
                    list = JsonConvert.DeserializeObject<List<ShopCartCookie>>(json);
                    if (list != null && list.Count > 0)
                    {
                        StringBuilder ids = new StringBuilder();
                        foreach (ShopCartCookie item in list)
                        {
                            if(item.Count>0)
                                ids.AppendFormat("{0} id={1}", (ids.ToString().IsNullOrWhiteSpace()) ? "" : "or", item.ID);
                        }
                        if (!ids.ToString().IsNullOrWhiteSpace())
                        {
                            dt = DataBaseProvider.GetInstance().GetCartItems(ids.ToString());
                            dt.Columns.Add("count", typeof(System.Int32));
                            dt.Columns.Add("totalPrice", typeof(System.Decimal));
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                ShopCartCookie shop = list.Find(delegate(ShopCartCookie p) { return p.ID == dt.Rows[i]["id"].ToString().ToInt(0); });
                                if (shop != null)
                                {
                                    dt.Rows[i]["count"] = shop.Count;
                                    dt.Rows[i]["totalPrice"] = shop.Count * dt.Rows[i]["price"].ToString().ToDecimal(0);
                                    totalPrice += shop.Count * dt.Rows[i]["price"].ToString().ToDecimal(0);
                                }
                            }
                        }
                    }
                }
                catch
                {
                }
            }
            return dt;
        }
        /// <summary>
        /// 把商品加入购物车
        /// </summary>
        /// <param name="code">商品加密id</param>
        /// <returns></returns>
        public static bool ADD(string code)
        {
            int id = code.DEC_Decode(BaseConfigs.DEC_KEY).ToInt(0);
            if (id > 0)
            {
                ShopCartCookie info = new ShopCartCookie();
                info.ID = id;
                info.Count = 1;
                return ShopCart.AddToCart(info);
            }
            else
                return false;
        }
    }
}
